import re
import time
from urllib import parse
from urllib.parse import unquote, urlparse, urlsplit
import requests
#先引入模块
from urllib.request import quote
from requests.adapters import HTTPAdapter
import requests  #导入模块
import maokoulingClass
#声明头部

def getShopUserId(url):
    header= {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0"}
    session = requests.session()
    session.mount('http://', HTTPAdapter(max_retries=3))
    session.mount('https://', HTTPAdapter(max_retries=3))
    try:
        html=session.get(url,headers=header, allow_redirects=False)
        # print(html.status_code)
        # print(session.headers)
        url = html.headers['Location']
        newurl = url.replace("https://s.click.taobao.com/t_js?tu=", "")
        # print(newurl)
        newurl = unquote(newurl)
        # print('123')
        # print(newurl)
        headers = {'Referer': url}
        session.headers = headers
        html=session.get(newurl, allow_redirects=False)
        realurl=html.headers['Location']
        # print(realurl)
        findid =re.compile(r'user_number_id=(\d+)')
        shopid= findid.findall(realurl)
        # print(result[0])
        return shopid[0]
    except Exception as e:
        print(e)
        return 000
# getShopUserId(url)


def getItemID(url):
    print("开始使用getItemID进行匹配")
    header= {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0"
    }
    session = requests.session()
    session.mount('http://', HTTPAdapter(max_retries=3))
    session.mount('https://', HTTPAdapter(max_retries=3))
    try:
        html=session.get(url,headers=header, allow_redirects=False)
        # print(html.status_code)
        # print(session.headers)
        referurl = html.headers['Location']
        requesturl = referurl.replace("https://s.click.taobao.com/t_js?tu=", "")
        requesturl = unquote(requesturl)
        # print('requesturl')
        # print(requesturl)
        # print('referurl')
        # print(referurl)
        headers = {'Referer': referurl}
        session.headers = headers
        html=session.get(requesturl,allow_redirects=False)
        # print(html.headers.__dict__)
        realurl=html.headers['location']
        # print('123222')
        # print(realurl)
        realurl = unquote(realurl)
        # print(realurl)
        str2 = re.compile(r'id=(\d+)&')
        itemid = str2.findall(realurl)
        # print(itemid)
        return itemid[0]
    except Exception as e:
        print("商品id出现问题")
        print(e)
        return '111'
# print(getShopUserId(url))
# print(getItemID(url))
def urlGetid(url):
    itemid = getItemID(url)
    shopid = getShopUserId(url)

    #如果itemid不为空，淘口令获得推广sclick链接
    print(123)
    abc = maokoulingClass.maokouling_ONE()
    if itemid != None:
        print("itemid123132")
        abc.itemid = itemid
        itemlink =maokoulingClass.tblink_get_gaoyong(abc)
        abc.userid = maokoulingClass.item_to_SELLID(abc)
        shoplink = maokoulingClass.userid_to_shopTBK_link(abc)
        print(itemlink)
        print(shoplink)
    else:
        print("shopid")
        abc.userid = shopid
        shoplink = maokoulingClass.userid_to_shopTBK_link(abc)
        print(shoplink)
def linktolink(sclik):
    url =f'https://api.open.21ds.cn/apiv1/sclicktoid?apkey=33e06833-f973-7708-a8aa-379b33b4c38c&sclickurl={sclik}'
    try:
        # print(url)
        html = requests.get(url)
        # print(html.json())
        itemJson = html.json()
        # print(itemJson)
        if itemJson['code'] != 200:
            print("API状态码错误")
            return None
        else:
            shopid = itemJson['data']
            print(shopid)
            return shopid
    except Exception as e:
        print(e)
        print('白名单限制')
        return None

url ='https://s.click.taobao.com/t?e=m%3D2%26s%3DAh%2FMzAKd9XIcQipKwQzePDAVflQIoZepK7Vc7tFgwiFRAdhuF14FMSxqWK16p8QVt4hWD5k2kjOlixRdQ5P%2FbRyIc2QYvMuncLvZQlVGpPkSG%2F1oPgxHusR08lhhnaucxgxdTc00KD8%3D'
print(getItemID(url))